package top.shaozuo.simple.user.web.listener;

import java.lang.management.ManagementFactory;
import java.util.logging.Logger;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import top.shaozuo.simple.context.ClassicComponentContext;
import top.shaozuo.simple.user.jmx.BlockEmails;

/**
 * Application Lifecycle Listener implementation class JmxExportListener
 *
 */
@WebListener
public class JmxExportListener implements ServletContextListener {

    private static final Logger logger = Logger.getLogger(JmxExportListener.class.getName());

    private static final String DOMAIN_NAME = "top.shaozuo.simple.user";

    /**
     * Default constructor.
     */
    public JmxExportListener() {
    }

    /**
     * @see ServletContextListener#contextDestroyed(ServletContextEvent)
     */
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    }

    /**
     * @see ServletContextListener#contextInitialized(ServletContextEvent)
     */
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        try {
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

            //为MBean创建ObjectName实例
            ObjectName helloName = new ObjectName(DOMAIN_NAME + ":name=BlockEmails");
            // 对象注册到MBeanServer上去
            BlockEmails emails = ClassicComponentContext.getInstance().getComponent("bean/BlockEmails");

            mbs.registerMBean(emails, helloName);

            logger.info("注册MBean成功");
        } catch (Exception e) {

        }
    }

}
